package com.celesea.configuration.web;


import com.alibaba.fastjson.JSON;
import com.celesea.configuration.security.CasProperties;
import com.celesea.configuration.web.bean.LoginInfo;
import com.celesea.framework.api.HttpKit;
import com.celesea.framework.api.Tip;
import com.celesea.framework.util.EnvUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;

/**
 * @author JackYuan
 */
@Controller
public class WebViewController {
    private static Logger logger = LoggerFactory.getLogger(WebViewController.class);

    @Autowired
    private CasProperties casProperties;

    @RequestMapping(value = {"/index"}, method = RequestMethod.GET)
    public void index(HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.info("cas登陆成功，跳转到商品BUI首页，参数：{}", JSON.toJSONString(request.getParameterMap()));
//        response.addCookie(new Cookie("brandId", String.valueOf(EnvUtil.getBrandId())));
        response.sendRedirect(casProperties.getBuiIndexUrl());
    }

    @ResponseBody
    @RequestMapping(value = {"loginInfo"}, method = RequestMethod.GET)
    public Tip<LoginInfo> loginInfo() {
        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setLoginAsBrand(EnvUtil.isBrandLogin());
        loginInfo.setBrandId(EnvUtil.getBrandId());
        // TODO 检查是否初始化成功
        logger.info("品牌Id：{}", EnvUtil.getBrandId());
        logger.info("门店Id：{}", EnvUtil.getShopId());
        logger.info("门店名称：{}", EnvUtil.getShopName());
        return HttpKit.success(loginInfo);
    }

    @ResponseBody
    @RequestMapping(value = "test1", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('admin1')")
    public String test1() {

        logger.info("品牌Id：{}", EnvUtil.getBrandId());
        logger.info("门店Id：{}", EnvUtil.getShopId());
        logger.info("门店名称：{}", EnvUtil.getShopName());

        return "test11";
    }

    @ResponseBody
    @RequestMapping(value = "v1/permit/test", method = RequestMethod.GET)
    public String test2() {
        return "v1/permit/test";
    }

    @ResponseBody
    @RequestMapping(value = "principal", method = RequestMethod.GET)
    public Object test(Principal principal) {
        return principal;
    }
}
